<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${!dataId ? '新增' : '编辑'}-部门`"
		width="680px"
		append-to-body
		:confirm-btn-loading="confirmBtnLoading"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :show-message="false" label-width="100px" size="medium">
			<el-row>
				<el-col :span="24">
					<el-form-item class="margin-bottom-10" label="上级部门">
						<el-cascader
							ref="tree"
							v-model="ruleForm.deptIds"
							:options="deptList"
							class="width-100-percent"
							placeholder="上级部门"
							:props="{
								value: 'id',
								label: 'name',
								checkStrictly: true
							}"
						></el-cascader>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="编号" prop="code">
						<el-input v-model="ruleForm.code" placeholder="编号" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="名称" prop="name">
						<el-input v-model="ruleForm.name" placeholder="名称" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="负责人">
						<remote-search-emp-input
							placeholder="负责人"
							only-key="leaderEmpId"
							query-name="leaderEmpName"
							:form-data="ruleForm"
							@on-select="onSelectEmpChange"
						></remote-search-emp-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="联系电话" prop="phone">
						<el-input v-model="ruleForm.phone" placeholder="联系电话" maxlength="11" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="邮箱" prop="email">
						<el-input v-model="ruleForm.email" placeholder="邮箱" maxlength="50" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="显示排序" prop="sort">
						<el-input-number v-model="ruleForm.sort" class="width-100-percent" controls-position="right" :min="0" />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="备注">
						<el-input v-model="ruleForm.remark" type="textarea" placeholder="" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</jk-dialog>

</template>
<script>
    import { statusList } from '../../../utils/jk/status-option-list';
    import { createTree, getFamily } from '../../../utils/jk/jk-tool';
    import { addDept, getDept, listDept, updateDept } from '../../../api/system/dept';
    import { validateArr } from '../../../utils/jk/validator';
    import remoteSearchEmpInput from '../../technology/order/components/remote-search-emp-input/index';
    export default {
        components: { remoteSearchEmpInput },
        props: {
            dataId: {
                type: [String, Number],
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            isAdd: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                confirmBtnLoading: false,
                deptList: [],
                showDialog: false,
                statusList: statusList,
                ruleForm: {
                    leaderEmpId: null,
                    leaderEmpName: null,
                    deptIds: [],
                    name: '',
                    code: '',
                    sort: 1,
                    remark: '',
                    status: 1
                },
                rules: {
                    deptIds: [{ required: true, validator: validateArr, trigger: 'change' }],
                    code: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onSelectEmpChange(e) {
                if (Object.keys(e).length) {
                    this.setDependentDataSalesman(e);
                }
            },
            setDependentDataSalesman(e) {
                this.$set(this.ruleForm, 'leaderEmpId', e.id);
                this.$set(this.ruleForm, 'leaderEmpName', e.name);
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.saveRequest().then(res => {
                            this.confirmBtnLoading = false;
                            if (res.data.status === 200) {
                                this.$tipsBar(this, 'save');
                                this.$emit('on-confirm');
                            }
                        });
                    }
                });
            },
            saveRequest() {
                this.confirmBtnLoading = true;
                if (this.isAdd) {
                    this.ruleForm.id = null;
                    this.ruleForm.parentId = this.ruleForm.deptIds[this.ruleForm.deptIds.length - 1];
                    return addDept(this.ruleForm);
                } else {
                    this.ruleForm.parentId = this.ruleForm.deptIds[this.ruleForm.deptIds.length - 1];
                    return updateDept(this.ruleForm);
                }
            },
            // 取消按钮
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data.ruleForm, this.$options.data().ruleForm);
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return getDept(this.dataId).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                        this.$set(this.ruleForm, 'deptIds', getFamily(this.originalData, this.dataId).ids);
                    }
                });
            },
            getDeptListRequest() {
                return listDept().then(res => {
                    if (res.data.status === 200) {
                        const resData = JSON.parse(JSON.stringify(res.data.res));
                        this.originalData = JSON.parse(JSON.stringify(resData));
                        this.deptList = createTree(resData, {});
                    }
                });
            },
            async getDependentData() {
                await this.getDeptListRequest();
                if (this.isAdd) {
                    this.$set(this.ruleForm, 'parentId', this.dataId);
                    this.$set(this.ruleForm, 'deptIds', getFamily(this.originalData, this.dataId).ids);
                }
                if (!this.isAdd && this.dataId) await this.getDetailRequest();
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
